package org.malred.sqlSession;

import org.malred.config.BoundSql;
import org.malred.pojo.Configuration;
import org.malred.pojo.MappedStatement;
import org.malred.utils.GenericTokenParser;
import org.malred.utils.ParameterMapping;
import org.malred.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) {
        try {
            // 1.注册驱动，获取连接
            Connection connection = configuration.getDataSource().getConnection();
            // 2.获取sql语句
            String sql = mappedStatement.getSql();
            // 转换sql语句 #{xxx} -> ?
            BoundSql boundSql = getBoundSql(sql);
            // 3.获取预处理对象
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTxt());
            // 4.填充参数
            String parameterType = mappedStatement.getParameterType();
            Class<?> parameterTypeClass = getClassType(parameterType);
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                // #{content}
                String content = parameterMapping.getContent();
                try {
                    // 反射获取属性值
                    Field declaredField = parameterTypeClass.getDeclaredField(content);
                    // 暴力访问
                    declaredField.setAccessible(true);
                    // params[0] -> object(eg. User)
                    Object o = declaredField.get(params[0]);

                    preparedStatement.setObject(i + 1, o);
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
            // 5.执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
            String resultType = mappedStatement.getResultType();
            Class<?> resultTypeClass = getClassType(resultType);
            ArrayList<Object> objects = new ArrayList<>();

            // 6.封装返回结果集
            while (resultSet.next()) {
                // 元数据
                ResultSetMetaData metaData = resultSet.getMetaData();
                // 创建实例
                Object o = resultTypeClass.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    // 字段名
                    String columnName = metaData.getColumnName(i);// 下标从1开始
                    // 字段值
                    Object value = resultSet.getObject(columnName);
                    // 使用反射,根据数据库表和实体的对应关系,完成封装
                    PropertyDescriptor propertyDescriptor =
                            new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    // 将值设置到对象的参数里
                    writeMethod.invoke(o, value);
                }
                objects.add(o);
            }
            return (List<E>) objects;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) {
        // 1.注册驱动，获取连接
        Connection connection = null;
        try {
            connection = configuration.getDataSource().getConnection();
        } catch (SQLException e) {
            rollback(connection, configuration.isAutoCommit());
            throw new RuntimeException(e);
        }
        // 开启事务
        try {
            connection.setAutoCommit(configuration.isAutoCommit());
        } catch (SQLException e) {
            rollback(connection, configuration.isAutoCommit());
            throw new RuntimeException(e);
        }
        // 2.获取sql语句
        String sql = mappedStatement.getSql();
        // 转换sql语句 #{xxx} -> ?
        BoundSql boundSql = getBoundSql(sql);
        // 3.获取预处理对象
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(boundSql.getSqlTxt());
        } catch (SQLException e) {
            rollback(connection, configuration.isAutoCommit());
            throw new RuntimeException(e);
        }
        // 4.填充参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            // #{content}
            String content = parameterMapping.getContent();
            try {
                // 反射获取属性值
                Field declaredField = parameterTypeClass.getDeclaredField(content);
                // 暴力访问
                declaredField.setAccessible(true);
                // params[0] -> object(eg. User)
                Object o = declaredField.get(params[0]);

                preparedStatement.setObject(i + 1, o);
            } catch (NoSuchFieldException e) {
                rollback(connection, configuration.isAutoCommit());
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                rollback(connection, configuration.isAutoCommit());
                throw new RuntimeException(e);
            } catch (SQLException e) {
                rollback(connection, configuration.isAutoCommit());
                throw new RuntimeException(e);
            }
        }
        // 5.执行sql
        int count = 0;
        try {
            count = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            rollback(connection, configuration.isAutoCommit());
            throw new RuntimeException(e);
        }
        return count;
    }

    @Override
    public void commit() {

    }

    private void rollback(Connection connection, boolean autoCommit) {
        System.out.println("something wrong! now rollback!");
        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据标签指定的参数类型加载class
     *
     * @param parameterType
     * @return
     * @throws ClassNotFoundException
     */
    private Class<?> getClassType(String parameterType) {
        if (parameterType != null) {
            Class<?> aClass = null;
            try {
                aClass = Class.forName(parameterType);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            return aClass;
        }
        return null;
    }

    /**
     * 对#{}解析：1.将#{}替换为? 2.解析出#{}里面的值进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser parser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 解析出来的sql
        String parseSql = parser.parse(sql);
        // #{}里解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }
}

